package com.zhangfb95.crosschain.plugin.container.java.fabric2.infra.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

public class CertUtil {

    /**
     * 获取私钥对象
     *
     * @param keyContent 私钥内容
     * @return 私钥对象
     */
    public static PrivateKey getPrivateKey(String keyContent) {
        ByteArrayInputStream is = new ByteArrayInputStream(keyContent.getBytes(StandardCharsets.UTF_8));

        PemReader pemReader = null;
        try {
            pemReader = new PemReader(new InputStreamReader(is));
            PemObject pem = pemReader.readPemObject();
            if (pem == null) {
                throw new IOException("The file does not represent a pem account.");
            }

            PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(pem.getContent());
            KeyFactory keyFactory = KeyFactory.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);

            return keyFactory.generatePrivate(encodedKeySpec);
        } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException e) {
            throw new RuntimeException(e);
        } finally {
            CloseUtil.closeQuietly(pemReader);
        }
    }
}
